package training.bms.presentation;

import java.util.List;

import org.apache.commons.lang.ObjectUtils;

import training.bms.business.Blog;
import training.bms.business.BlogController;
import training.bms.business.BlogSearchOptions;
import training.bms.business.Post;
import training.bms.business.Tag;
import training.bms.business.TagController;
import training.bms.business.TagSearchOptions;
import training.framework.business.BusinessException;
import training.framework.presentation.AbstractEntityPanel;

public class PostPanel extends AbstractEntityPanel<Integer, Post> {
	private List<Blog> blogs;
	private List<Tag> tags;
	
	public PostPanel() {
		this(new Post());
	}

	public PostPanel(Post post) {
		setEntity(post);
		this.blogs = searchBlogs();
		this.tags = searchTags();
	}
		
	private List<Blog> searchBlogs() {
		BlogSearchOptions options = new BlogSearchOptions();
		BlogController controller = new BlogController();
		return controller.searchEntity(options);
	}	
	
	private List<Tag> searchTags() {
		TagSearchOptions options = new TagSearchOptions();
		TagController controller = new TagController();
		return controller.searchEntity(options);
	}
	
	public List<Blog> getBlogs() {
		return blogs;
	}
	
	public void setBlogs(List<Blog> blogs) {
		this.blogs = blogs;
	}
	
	public List<Tag> getTags() {
		return tags;
	}
	
	public void setBlogIdentifier(Integer identifier) {
		Blog blog = searchBlog(identifier);
		getEntity().setBlog(blog);
	}
	
	private Blog searchBlog(Integer identifier) {
		for (Blog blog : blogs) {
			if (ObjectUtils.equals(blog.getIdentifier(), identifier)) {
				return blog;
			}
		}
		return null;
	}

	public Integer getBlogIdentifier() {
		Blog blog = getEntity().getBlog();
		if (blog == null) {
			return null;
		} else {
			return blog.getIdentifier();
		}
	}	
	
	public void setSelectedTags(String[] selectedTags){
		Post post = getEntity();
		post.clearTags();
		
		for(String selectedTag : selectedTags){
			int tagIdentifier = Integer.parseInt(selectedTag);
			Tag tag = searchTag(tagIdentifier);
			if(tag != null){
				post.addTag(tag);
			}
		}
	}
	
	public String[] getSelectedTags(){
		Post post = getEntity();
		List<Tag> tags = post.getTags();
		String[] selectedTags = new String[tags.size()];
		int index = 0;
		for(Tag tag : tags){
			Integer identifier = tag.getIdentifier();
			selectedTags[index] = Integer.toString(identifier);
			index++;
		}
		return selectedTags;
	}
	
	private Tag searchTag(Integer identifier) {
		for (Tag tag : tags) {
			if (ObjectUtils.equals(tag.getIdentifier(), identifier)) {
				return tag;
			}
		}
		return null;
	}
	
	
			
	
}
